#include "thememanager.h"
#include <QPalette>
#include <QApplication>
#include <QSettings>
#include <QFile>
#include <QDebug>

/**
 * @brief 构造函数，初始化主题管理器
 * @param parent 父对象
 */
ThemeManager::ThemeManager(QObject* parent) : QObject(parent)
{
    initializeBuiltInThemes();
}

/**
 * @brief 初始化内置主题
 * 创建并注册所有预定义的主题，包括默认、深色、浅色、蓝色和绿色主题
 */
void ThemeManager::initializeBuiltInThemes() {
    // 默认主题
    QPalette defaultPalette = qApp->palette();
    m_palettes[DEFAULT_THEME] = defaultPalette;
    m_themeDescriptions[DEFAULT_THEME] = "Default theme";

    // 深色主题
    QPalette darkPalette;
    darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
    darkPalette.setColor(QPalette::WindowText, Qt::white);
    darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
    darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
    darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
    darkPalette.setColor(QPalette::ToolTipText, Qt::black);
    darkPalette.setColor(QPalette::Text, Qt::white);
    darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
    darkPalette.setColor(QPalette::ButtonText, Qt::white);
    darkPalette.setColor(QPalette::BrightText, Qt::red);
    darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
    darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
    darkPalette.setColor(QPalette::HighlightedText, Qt::black);
    m_palettes[DARK_THEME] = darkPalette;
    m_themeDescriptions[DARK_THEME] = "Dark theme";

    // 浅色主题
    QPalette lightPalette;
    lightPalette.setColor(QPalette::Window, QColor(240, 240, 240));
    lightPalette.setColor(QPalette::WindowText, Qt::black);
    lightPalette.setColor(QPalette::Base, QColor(255, 255, 255));
    lightPalette.setColor(QPalette::AlternateBase, QColor(245, 245, 245));
    lightPalette.setColor(QPalette::ToolTipBase, Qt::white);
    lightPalette.setColor(QPalette::ToolTipText, Qt::black);
    lightPalette.setColor(QPalette::Text, Qt::black);
    lightPalette.setColor(QPalette::Button, QColor(240, 240, 240));
    lightPalette.setColor(QPalette::ButtonText, Qt::black);
    lightPalette.setColor(QPalette::BrightText, Qt::red);
    lightPalette.setColor(QPalette::Link, QColor(0, 0, 255));
    lightPalette.setColor(QPalette::Highlight, QColor(76, 163, 224));
    lightPalette.setColor(QPalette::HighlightedText, Qt::black);
    m_palettes[LIGHT_THEME] = lightPalette;
    m_themeDescriptions[LIGHT_THEME] = "Light theme";

    // 蓝色主题
    QPalette bluePalette;
    bluePalette.setColor(QPalette::Window, QColor(240, 248, 255));
    bluePalette.setColor(QPalette::WindowText, Qt::black);
    bluePalette.setColor(QPalette::Base, QColor(230, 240, 250));
    bluePalette.setColor(QPalette::AlternateBase, QColor(220, 230, 240));
    bluePalette.setColor(QPalette::ToolTipBase, Qt::white);
    bluePalette.setColor(QPalette::ToolTipText, Qt::black);
    bluePalette.setColor(QPalette::Text, Qt::black);
    bluePalette.setColor(QPalette::Button, QColor(100, 149, 237));
    bluePalette.setColor(QPalette::ButtonText, Qt::white);
    bluePalette.setColor(QPalette::BrightText, Qt::red);
    bluePalette.setColor(QPalette::Link, QColor(0, 0, 255));
    bluePalette.setColor(QPalette::Highlight, QColor(65, 105, 225));
    bluePalette.setColor(QPalette::HighlightedText, Qt::white);
    m_palettes[BLUE_THEME] = bluePalette;
    m_themeDescriptions[BLUE_THEME] = "Blue theme";

    // 绿色主题
    QPalette greenPalette;
    greenPalette.setColor(QPalette::Window, QColor(240, 255, 240));         // 浅绿色背景
    greenPalette.setColor(QPalette::WindowText, Qt::black);                 // 黑色文字
    greenPalette.setColor(QPalette::Base, QColor(220, 255, 220));           // 基础控件背景
    greenPalette.setColor(QPalette::AlternateBase, QColor(200, 250, 200));  // 替代背景
    greenPalette.setColor(QPalette::ToolTipBase, Qt::white);                // 提示框背景
    greenPalette.setColor(QPalette::ToolTipText, Qt::black);                // 提示框文字
    greenPalette.setColor(QPalette::Text, Qt::black);                       // 主要文本
    greenPalette.setColor(QPalette::Button, QColor(144, 238, 144));         // 按钮背景
    greenPalette.setColor(QPalette::ButtonText, Qt::black);                 // 按钮文字
    greenPalette.setColor(QPalette::BrightText, Qt::red);                   // 亮色文本
    greenPalette.setColor(QPalette::Link, QColor(0, 100, 0));               // 链接颜色
    greenPalette.setColor(QPalette::Highlight, QColor(60, 179, 113));       // 高亮颜色
    greenPalette.setColor(QPalette::HighlightedText, Qt::white);            // 高亮文本
    m_palettes[GREEN_THEME] = greenPalette;
    m_themeDescriptions[GREEN_THEME] = "Green theme";

    // 加载每个主题的样式表
    m_styleSheets.clear();
    m_styleSheets[DEFAULT_THEME] = loadStyleSheet(":/qss/Default.css");
    m_styleSheets[DARK_THEME] = loadStyleSheet(":/qss/Dark.css");
    m_styleSheets[LIGHT_THEME] = loadStyleSheet(":/qss/Light.css");
    m_styleSheets[BLUE_THEME] = loadStyleSheet(":/qss/Blue.css");
    m_styleSheets[GREEN_THEME] = loadStyleSheet(":/qss/Green.css");
}

/**
 * @brief 初始化主题系统
 * 加载保存的主题并检测系统主题
 */
void ThemeManager::initialize() {
    loadSavedTheme();
    detectSystemTheme();
}

/**
 * @brief 设置当前主题
 * @param themeName 主题名称
 * @return 设置成功返回true，主题不存在返回false
 */
bool ThemeManager::setTheme(const QString& themeName) {
    if (!themeExists(themeName)) {
        return false;
    }

    QString oldTheme = m_currentTheme;
    m_currentTheme = themeName;
    this->applyTheme(themeName);
    this->saveCurrentTheme();

    // 发出主题切换信号
    if (oldTheme != themeName) {
        emit themeChanged(themeName);
    }
    return true;
}

/**
 * @brief 设置当前主题
 * @param themeName 主题名称
 * @return 设置成功返回true，主题不存在返回false
 */
bool ThemeManager::setTheme(ThemeManager::ThemeQssEnum theme)
{
    QString oldTheme = m_currentTheme;
    m_currentTheme = themeToString(theme);

    if (!themeExists(m_currentTheme)) {
        return false;
    }

    this->applyTheme(m_currentTheme);
    this->saveCurrentTheme();

    // 发出主题切换信号
    if (oldTheme != m_currentTheme) {
        emit themeChanged(m_currentTheme);
    }
    return true;
}

/**
 * @brief 获取当前主题名称
 * @return 当前主题的名称
 */
QString ThemeManager::currentTheme() const {
    return m_currentTheme;
}

/**
 * @brief 获取所有可用主题的列表
 * @return 包含所有主题名称的字符串列表
 */
QStringList ThemeManager::availableThemes() const {
    return m_palettes.keys();
}

/**
 * @brief 检查主题是否存在
 * @param themeName 要检查的主题名称
 * @return 主题存在返回true，不存在返回false
 */
bool ThemeManager::themeExists(const QString& themeName) const {
    return m_palettes.contains(themeName);
}

/**
 * @brief 保存当前主题设置到配置文件
 * 将当前主题名称保存到应用程序目录下的config.ini文件中
 */
void ThemeManager::saveCurrentTheme() {
    QString configPath = QCoreApplication::applicationDirPath() + "/config.ini";
    QSettings settings(configPath, QSettings::IniFormat);
    settings.setValue("AppTheme/theme", m_currentTheme);
    settings.sync();
}

/**
 * @brief 加载保存的主题设置
 * 从配置文件中读取保存的主题名称，如果不存在则使用默认主题
 */
void ThemeManager::loadSavedTheme() {
    QString configPath = QCoreApplication::applicationDirPath() + "/config.ini";
    QSettings settings(configPath, QSettings::IniFormat);
    QString savedTheme = settings.value("AppTheme/theme", DEFAULT_THEME).toString();
    if (themeExists(savedTheme)) {
        setTheme(savedTheme);
    } else {
        setTheme(DEFAULT_THEME);
    }
}

/**
 * @brief 检测系统主题
 * 根据不同操作系统的主题设置自动调整应用主题
 */
void ThemeManager::detectSystemTheme() {
#ifdef Q_OS_WIN
    // Windows 10及以上版本检测
    QSettings registrySettings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
                               QSettings::NativeFormat);
    bool isSystemDark = registrySettings.value("AppsUseLightTheme", 1).toInt() == 0;

    if (isSystemDark && m_currentTheme != DARK_THEME) {
        setTheme(DARK_THEME);
    } else if (!isSystemDark && m_currentTheme != LIGHT_THEME) {
        setTheme(LIGHT_THEME);
    }

#elif defined(Q_OS_MACOS)
    // macOS检测
    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_14) {
        // macOS 10.14+支持暗色模式
        CFStringRef darkModeKey = CFStringCreateWithCString(kCFAllocatorDefault,
                                                            "AppleInterfaceTheme",
                                                            kCFStringEncodingUTF8);
        CFStringRef interfaceTheme = (CFStringRef)CFPreferencesCopyAppValue(darkModeKey,
                                                                            kCFPreferencesCurrentApplication);

        bool isSystemDark = (interfaceTheme != nullptr &&
                CFStringCompare(interfaceTheme, CFSTR("Dark"), 0) == kCFCompareEqualTo);

        if (isSystemDark && m_currentTheme != DARK_THEME) {
            setTheme(DARK_THEME);
        } else if (!isSystemDark && m_currentTheme != LIGHT_THEME) {
            setTheme(LIGHT_THEME);
        }

        if (interfaceTheme) {
            CFRelease(interfaceTheme);
        }
        CFRelease(darkModeKey);
    }

#elif defined(Q_OS_LINUX)
    // Linux检测
    // 可以根据桌面环境检测主题
    // 例如GNOME、KDE等

#endif
}

/**
 * @brief 应用系统主题
 * 根据系统设置应用相应的主题
 */
void ThemeManager::applySystemTheme() {
    // 根据系统主题设置应用相应的主题
    // 例如在Windows上检测深色/浅色模式
}

/**
 * @brief 获取当前调色板
 * @return 当前主题的QPalette对象
 */
QPalette ThemeManager::currentPalette() const {
    return m_palettes.value(m_currentTheme);
}

/**
 * @brief 获取当前样式表
 * @return 当前主题的样式表内容
 */
QString ThemeManager::currentStyleSheet() const {
    return m_styleSheets.value(m_currentTheme);
}

/**
 * @brief 应用指定主题
 * @param themeName 要应用的主题名称
 */
void ThemeManager::applyTheme(const QString& themeName) {
    if (!themeExists(themeName)) {
        qWarning() << "Cannot apply non-existent theme:" << themeName;
        return;
    }

    // 应用调色板
    QApplication::setPalette(m_palettes[themeName]);

    // 应用样式表
    QString styleSheet = m_styleSheets.value(themeName);
    if (!styleSheet.isEmpty()) {
        qApp->setStyleSheet(styleSheet);
    } else {
        qApp->setStyleSheet("");
    }
}

/**
 * @brief 加载样式表文件
 * @param filePath 样式表文件路径
 * @return 样式表内容字符串，如果文件不存在则返回空字符串
 */
QString ThemeManager::loadStyleSheet(const QString& filePath) {
    QFile file(filePath);
    if (!file.exists()) {
        return QString();
    }

    file.open(QFile::ReadOnly);
    QString styleSheet = QLatin1String(file.readAll());
    file.close();
    return styleSheet;
}
